<?php
namespace common\models;

use Yii;
use yii\base\Exception;

/**
 * /**
 * 获取邮箱验证码
 * @return array
 */

// *
// * Class Email
// * @package common\models
// */
class Email
{

    public $registerByEmail = '此次用于注册的邮箱验证码为{code}，请在{time}分钟之内输入，切勿告知他人';
    public $forgetPasswordByEmail = '此次用于找回密码的邮箱验证码为{code}，请在{time}分钟之内输入，切勿告知他人';
    public $setEmail = '此次用于绑定的邮箱验证码为{code}，请在{time}分钟之内输入，切勿告知他人';
//    public $forgetByEmailTmp = '此次用于注册的邮箱验证码为'.$code.'，请在'.$time.'分钟之内输入，切勿告知他人';
    const CONTENT_MAP = [
        CacheKeys::CACHE_CODE_TYPE_REGISTER_CODE => '此次用于注册的邮箱验证码为{code}，请在{time}分钟之内输入，切勿告知他人',
        CacheKeys::CACHE_CODE_TYPE_RESET_CODE => '此次用于重置密码的邮箱验证码为{code}，请在{time}分钟之内输入，切勿告知他人',
        CacheKeys::CACHE_CODE_TYPE_FORGET_CODE => '此次用于找回密码的邮箱验证码为{code}，请在{time}分钟之内输入，切勿告知他人',
        CacheKeys::CACHE_CODE_TYPE_LOGIN => '此次登录的验证码{code},请在{time}分钟内输入，切勿告知他人',
        CacheKeys::CACHE_CODE_TYPE_SET_CREDIT => '您正在重新设置资金密码，验证码为{code},请在{time}分钟之内输入，打死不要告诉别人',
        CacheKeys::CACHE_CODE_TYPE_BIND_PHONE => '您正在绑定手机，验证码为{code},请在{time}分钟之内输入，打死不要告诉别人',
        CacheKeys::CACHE_CODE_TYPE_BIND_SOURCE_EMAIL => '此次用于绑定的邮箱验证码为{code}，请在{time}分钟之内输入，切勿告知他人',
        CacheKeys::CACHE_CODE_TYPE_BIND_EMAIL => '此次用于绑定的邮箱验证码为{code}，请在{time}分钟之内输入，切勿告知他人',
    ];

    /**
     *  邮箱发送集成方法
     * @param string $sendEmail
     * @param string $sendTitle
     * @param string $type
     * @param int $time
     * @return array
     */
    public function sendEmail($sendEmail = '', $sendTitle = '', $type = '', $time = 5)
    {
        $code = rand(100000, 999999);
//        $code = 123;
        $cacheKey = Functions::getVerifyKey($sendEmail, $type);
        try {
            if (!array_key_exists($type, static::CONTENT_MAP)) {
                throw new Exception('未知类型');
            }
            $content = static::CONTENT_MAP[$type];
            //校验时间间隔
            $cache = Yii::$app->cache;
            $lastData = json_decode($cache->get($cacheKey), true);
            if (!empty($lastData) && isset($lastData['send_time'])) {
                if ($lastData['expire_time'] > time()) {
//                    throw new Exception('时间间隔小于60秒', 2000);
                }
            }

            if($sendEmail == '') {
                throw new Exception('邮箱不存在');
            }

            if($sendTitle == '') {
                throw new Exception('邮箱标题不能为空');
            }

            $sendContent =  str_replace('{code}',$code,$content);
            $sendContent =  str_replace('{time}',$time,$sendContent);

            if($sendContent == '') {
                throw new Exception('发送内容不能为空');
            }

            $sendEmail = trim($sendEmail);
            $sendTitle = trim($sendTitle);
            $sendContent = trim($sendContent);
            $mail = Yii::$app->mailer->compose();
            $mail->setTo($sendEmail);//接收人邮箱
            $mail->setSubject($sendTitle);    //邮件标题
            $mail->setHtmlBody($sendContent);


            $res = $mail->send();
            if(!$res) {
                throw new Exception('邮件发送失败');
            }
            $data = [
                'code' => $code,
                'expire_time' => time() + $time * 60,
                'send_time' => time(),
                'to' => $sendEmail,
            ];

            $cache->set($cacheKey, json_encode($data), Yii::$app->params['user.passwordResetTokenExpire']);
            return Functions::formatJson(1000,'邮件发送成功。', $data);
        } catch (Exception $e) {
            return Functions::formatJson(2000,$e->getMessage());
        }
    }


    public function sendRestfulEmail($sendEmail = '',$sendTitle = '',$type = '',$time = 5)
    {
        $code = rand(100000, 999999);
        $content = $this->$type;
        try {
            //校验时间间隔
            $session = Yii::$app->getSession();
            $lastData = $session->get($type);
            if (!empty($lastData) && isset($lastData['send_time'])) {
                if ($lastData['send_time'] + 60 > time()) {
                    throw new Exception('时间间隔小于60秒', 2000);
                }
            }

            if($sendEmail == '') {
                throw new Exception('邮箱不存在');
            }

            if($sendTitle == '') {
                throw new Exception('邮箱标题不能为空');
            }

            $sendContent =  str_replace('{code}',$code,$content);
            $sendContent =  str_replace('{time}',$time,$sendContent);

            if($sendContent == '') {
                throw new Exception('发送内容不能为空');
            }
            $sendEmail = trim($sendEmail);
            $sendTitle = trim($sendTitle);
            $sendContent = trim($sendContent);
            $mail = \Yii::$app->mailer->compose();
            $mail->setTo($sendEmail);//接收人邮箱
            $mail->setSubject($sendTitle);    //邮件标题
            $mail->setHtmlBody($sendContent);

            $res = $mail->send();
            if(!$res) {
                throw new Exception('邮件发送失败');
            }

            $session = Yii::$app->getSession();
            $data = [
                'code' => $code,
                'expire_time' => time() + $time * 60,
                'send_time' => time(),
                'email' => $sendEmail,
            ];
            $session->set($type, $data);
            return Functions::formatJson(0,'邮件发送成功。');
        } catch (Exception $e) {
            return Functions::formatJson(1,$e->getMessage());
        }
    }


    /**
     * 为了通知发送邮件
     * @param string $sendEmail
     * @param string $sendTitle
     * @param string $sendContent
     * @return array
     */
    public static function sendEmailForInform ($sendEmail = '',$sendTitle = '', $sendContent = '') {
        try {
            if($sendEmail == '') {
                throw new Exception('邮箱不存在');
            }

            if($sendTitle == '') {
                throw new Exception('邮箱标题不能为空');
            }

            if($sendContent == '') {
                throw new Exception('发送内容不能为空');
            }

            $sendEmail = trim($sendEmail);
            $sendTitle = trim($sendTitle);
            $sendContent = trim($sendContent);
            $mail = Yii::$app->mailer->compose();
//            $mail->setTo($sendEmail);//接收人邮箱
            $mail->setTo($sendEmail);//接收人邮箱
            $mail->setSubject($sendTitle);    //邮件标题
            $mail->setHtmlBody($sendContent);

            $res = $mail->send();

            if(!$res) {
                throw new Exception('邮件发送失败');
            }

            return Functions::formatJson(1000,'邮件发送成功。');
        } catch (Exception $e) {
            return Functions::formatJson(2000,$e->getMessage());
        }
    }
}
